package whitelistservice

import (
	"context"
	"fmt"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/code"
	"vpn-management-server/src/dao/whitelistdao"
	"vpn-management-server/src/model/whitelistmodel"
)

func AddWhitelistService(ctx context.Context, ugid int, whitelist []*Whitelistmodel.WhiteItem, response *network.NetResponse) {
	var phoneList Whitelistmodel.PhoneList
	for _, item := range whitelist {
		phoneList.PhoneList = append(phoneList.PhoneList, item.Phone)
	}
	if i, ok := whitelistdao.HasPhones(phoneList.PhoneList); !ok && i == -1 {
		i, err := whitelistdao.AddWhiteList(ugid, whitelist)
		if err != nil && i != -1 {
			logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), fmt.Sprintf("add phone %s fail,err", phoneList.PhoneList[i]), err)
			response.Code = code.BAD_REQUEST
			response.ErrorMsg = "add whitelist fail"
		}
		response.Code = code.SUCCESS
		logger.Logger.Infof("add whitelist success")
	} else {
		logger.Logger.Errorf("phone %s is already existed\n", phoneList.PhoneList[i])
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "phone is already existed"
	}
}

func ValidateWhiteItemService(ctx context.Context, phone string, invitation string) bool {
	if whiteItem := whitelistdao.GetWhiteItemByPhone(phone); whiteItem != nil {
		if whiteItem.Invitation == invitation {
			return true
		}
		logger.Logger.Debug("invitation not match")
	}
	logger.Logger.Debug("phone not match")
	return false
}
